package collector

import (
	"database/sql"
	"log/slog"

	"github.com/prometheus/client_golang/prometheus"
)

const (
	//获取数据库实例基本信息
	labelinfoQuery = `select (select INSTANCE_NAME  FROM v$instance) instance_name ,
	(select substr(svr_version,instr(svr_version,'(')) FROM v$instance) version,
	(select CASE SF_GET_UNICODE_FLAG() WHEN '0' THEN 'GBK18030' WHEN '1' then 'UTF-8' when '2' then 'EUC-KR' end ) charset,
	(select PAGE()/1024 || 'K' ) page_size,
	(select SF_GET_EXTENT_SIZE()) extent_size,
	(select SF_GET_CASE_SENSITIVE_FLAG()) case_sensitive,
	(select permanent_magic) permanent_magic,
	(select db_magic from v$rlog) db_magic
	from dual;`
	dbInfo = "information"
)

var (
	dbInfoDesc = prometheus.NewDesc(
		prometheus.BuildFQName(namespace, dbInfo, "basic"),
		"The DM basic information",
		[]string{"instance_name", "version", "charset", "page_size", "extent_size", "case_sensitive", "permanent_magic", "db_magic"}, nil,
	)
)

// 达梦数据库基本信息。
type DMInfo struct {
	instance_name   string
	version         string
	charset         string
	page_size       string
	extent_size     string
	case_sensitive  string
	permanent_magic string
	db_magic        string
}

// 将dm_info结构体值转换为字符串切片。
func (di DMInfo) convertToLabelValues() []string {
	var lvs = []string{di.instance_name, di.version, di.charset, di.page_size, di.extent_size, di.case_sensitive, di.permanent_magic, di.db_magic}

	return lvs
}

func (DMInfo) Name() string {
	return "dmInfo"
}
func (di DMInfo) Scrape(db *sql.DB, ch chan<- prometheus.Metric, backupPath string, logger *slog.Logger) error {

	if err := db.QueryRow(labelinfoQuery).Scan(&di.instance_name, &di.version, &di.charset, &di.page_size, &di.extent_size, &di.case_sensitive, &di.permanent_magic, &di.db_magic); err != nil {
		ch <- prometheus.MustNewConstMetric(
			dbInfoDesc, prometheus.GaugeValue, 0,
			di.convertToLabelValues()...,
		)
		logger.Error("Error Query dm basic info", "error", err)
		return err
	}

	ch <- prometheus.MustNewConstMetric(
		dbInfoDesc, prometheus.GaugeValue, 1,
		di.convertToLabelValues()...,
	)

	return nil
}

func init() {
	RegisterScraper("dmInfo", DMInfo{})
}

var _ Scraper = DMInfo{}
